import re
import socket
from os import path
from time import sleep, localtime, strftime, time
from urllib import parse, request
import base64

from .dao import Dao


def parse_recv(data):
    res = {}
    it = re.finditer(r'<script>(.+?)</script>', data)
    for match in it:
        group = match.group(1)
        params = group.split('=', 1)
        table_name = re.sub(r'([A-Z])', r'_\1', params[0]).upper()
        pairs = [('createTime', time())]
        items = params[1][1:-1].split(',')
        for item in items:
            pairs.append(item.split(':'))
        res[table_name] = pairs
    return res


def socket_request(remote, req_line):
    res = None
    try:
        s = socket.socket()
        s.connect(remote)
        s.send(req_line.encode())
        data = s.recv(5120).decode('gbk')
        res = parse_recv(data)
    except Exception as error:
        print('sync_task request->', error)
    finally:
        s.close()
    return res


def sync_ip():
    try:
        with request.urlopen('http://ip.42.pl/raw') as f:
            if int(f.status) == 200:
                my_ip = f.read().decode('utf-8')
                url = 'http://ddns.oray.com/ph/update?hostname=zpfei.picp.net&myip=%s' % my_ip
                req = request.Request(url)
                auth = base64.b64encode('zzpfei:a736406266'.encode()).decode()
                req.add_header('Authorization', 'Basic %s' % auth)
                with request.urlopen(req) as ff:
                    print(ff.read())
    except Exception as error:
        print('同步外网IP失败', error)


def save_tem(cf):
    i = 0
    dao = Dao(cf['db'])
    while True:
        try:
            if i % 300 == 0:
                sync_ip()
            i += 1
            if path.exists(cf['error_file']):
                res = socket_request(tuple(cf['remote']), 'GET / HTTP/1.1')
                batch_sql = []
                if res:
                    for table in res:
                        pairs = list(zip(*res[table]))
                        batch_sql.append('insert into %s %s values %s' % (table, str(pairs[0]), str(pairs[1])))
                        dao.batch(batch_sql)
                now = strftime("%Y-%m-%d %H:%M:%S", localtime())
                print('[%s][sync_task][NO-%d]-->本次共插入%d条数据!' % (now, i, len(batch_sql)))
        except Exception as error:
            print('[sync_task] error->', error)

        sleep(cf['interval'])
